/**
 * 多端分享工具
 */
import platform from './platform.js'

// 分享到微信
export const shareToWeChat = (options = {}) => {
  return new Promise((resolve, reject) => {
    const shareData = {
      title: options.title || '圈子社交',
      desc: options.desc || '发现有趣的圈子，分享精彩生活',
      link: options.link || '',
      imgUrl: options.imgUrl || ''
    }
    
    // #ifdef MP-WEIXIN
    // 微信小程序分享
    uni.showShareMenu({
      withShareTicket: true,
      success: resolve,
      fail: reject
    })
    // #endif
    
    // #ifdef H5
    // H5环境分享
    if (platform.isWeChat()) {
      // 微信浏览器中使用微信JS-SDK分享
      if (window.wx) {
        window.wx.ready(() => {
          window.wx.updateAppMessageShareData({
            title: shareData.title,
            desc: shareData.desc,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: resolve,
            fail: reject
          })
          
          window.wx.updateTimelineShareData({
            title: shareData.title,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: resolve,
            fail: reject
          })
        })
      } else {
        // 普通浏览器使用Web Share API或复制链接
        if (navigator.share) {
          navigator.share({
            title: shareData.title,
            text: shareData.desc,
            url: shareData.link
          }).then(resolve).catch(reject)
        } else {
          // 复制链接到剪贴板
          copyToClipboard(shareData.link).then(() => {
            uni.showToast({
              title: '链接已复制到剪贴板',
              icon: 'success'
            })
            resolve()
          }).catch(reject)
        }
      }
    } else {
      // 非微信环境
      if (navigator.share) {
        navigator.share({
          title: shareData.title,
          text: shareData.desc,
          url: shareData.link
        }).then(resolve).catch(reject)
      } else {
        copyToClipboard(shareData.link).then(() => {
          uni.showToast({
            title: '链接已复制到剪贴板',
            icon: 'success'
          })
          resolve()
        }).catch(reject)
      }
    }
    // #endif
    
    // #ifdef APP-PLUS
    // APP环境分享
    plus.share.getServices((services) => {
      const wechatService = services.find(s => s.id === 'weixin')
      if (wechatService) {
        plus.share.sendWithSystem({
          type: 'text',
          content: `${shareData.title}\n${shareData.desc}\n${shareData.link}`
        }, resolve, reject)
      } else {
        reject(new Error('未安装微信'))
      }
    }, reject)
    // #endif
  })
}

// 分享帖子
export const sharePost = (post) => {
  const shareData = {
    title: post.title || '精彩帖子分享',
    desc: post.content ? post.content.substring(0, 100) + '...' : '来看看这个有趣的内容',
    link: `${window.location.origin}/pages/post/detail?id=${post.id}`,
    imgUrl: post.mediaList && post.mediaList.length > 0 ? post.mediaList[0] : ''
  }
  
  return shareToWeChat(shareData)
}

// 分享圈子
export const shareTopic = (topic) => {
  const shareData = {
    title: topic.name || '精彩圈子推荐',
    desc: topic.description ? topic.description.substring(0, 100) + '...' : '加入这个有趣的圈子',
    link: `${window.location.origin}/pages/circles/detail?id=${topic.id}`,
    imgUrl: topic.avatar || topic.cover || ''
  }
  
  return shareToWeChat(shareData)
}

// 复制到剪贴板
export const copyToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(resolve).catch(reject)
    } else {
      // 兼容旧版浏览器
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      try {
        document.execCommand('copy')
        document.body.removeChild(textArea)
        resolve()
      } catch (err) {
        document.body.removeChild(textArea)
        reject(err)
      }
    }
    // #endif
    
    // #ifdef MP-WEIXIN || APP-PLUS
    uni.setClipboardData({
      data: text,
      success: resolve,
      fail: reject
    })
    // #endif
  })
}

// 生成分享海报
export const generateSharePoster = (options = {}) => {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    // H5环境使用Canvas生成海报
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    canvas.width = options.width || 750
    canvas.height = options.height || 1334
    
    // 绘制背景
    ctx.fillStyle = options.backgroundColor || '#ffffff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 绘制标题
    ctx.fillStyle = options.titleColor || '#333333'
    ctx.font = `bold ${options.titleSize || 32}px Arial`
    ctx.textAlign = 'center'
    ctx.fillText(options.title || '分享海报', canvas.width / 2, 100)
    
    // 绘制内容
    if (options.content) {
      ctx.fillStyle = options.contentColor || '#666666'
      ctx.font = `${options.contentSize || 24}px Arial`
      ctx.textAlign = 'left'
      
      const lines = wrapText(ctx, options.content, canvas.width - 80)
      lines.forEach((line, index) => {
        ctx.fillText(line, 40, 200 + index * 40)
      })
    }
    
    // 绘制二维码（如果有）
    if (options.qrCode) {
      const img = new Image()
      img.onload = () => {
        ctx.drawImage(img, canvas.width - 200, canvas.height - 200, 160, 160)
        resolve(canvas.toDataURL('image/png'))
      }
      img.onerror = reject
      img.src = options.qrCode
    } else {
      resolve(canvas.toDataURL('image/png'))
    }
    // #endif
    
    // #ifdef MP-WEIXIN || APP-PLUS
    // 小程序和APP环境暂不支持Canvas生成海报
    reject(new Error('当前环境不支持生成海报'))
    // #endif
  })
}

// 文本换行处理
const wrapText = (ctx, text, maxWidth) => {
  const words = text.split('')
  const lines = []
  let currentLine = ''
  
  for (let i = 0; i < words.length; i++) {
    const testLine = currentLine + words[i]
    const metrics = ctx.measureText(testLine)
    const testWidth = metrics.width
    
    if (testWidth > maxWidth && i > 0) {
      lines.push(currentLine)
      currentLine = words[i]
    } else {
      currentLine = testLine
    }
  }
  lines.push(currentLine)
  
  return lines
}

// 保存图片到相册
export const saveImageToAlbum = (imagePath) => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    uni.authorize({
      scope: 'scope.writePhotosAlbum',
      success: () => {
        uni.saveImageToPhotosAlbum({
          filePath: imagePath,
          success: () => {
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            })
            resolve()
          },
          fail: reject
        })
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要您授权保存相册',
          showCancel: false,
          success: () => {
            uni.openSetting()
          }
        })
        reject(new Error('用户拒绝授权'))
      }
    })
    // #endif
    
    // #ifdef H5
    // H5环境下载图片
    const link = document.createElement('a')
    link.href = imagePath
    link.download = `share_poster_${Date.now()}.png`
    link.click()
    
    uni.showToast({
      title: '开始下载',
      icon: 'success'
    })
    resolve()
    // #endif
    
    // #ifdef APP-PLUS
    uni.saveImageToPhotosAlbum({
      filePath: imagePath,
      success: () => {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        resolve()
      },
      fail: reject
    })
    // #endif
  })
}

export default {
  shareToWeChat,
  sharePost,
  shareTopic,
  copyToClipboard,
  generateSharePoster,
  saveImageToAlbum
}